<?php


namespace App\library\services\lib\tencentCloud;

use App\library\services\ConfigService;
use Illuminate\Support\Facades\Redis;

class Cos
{
    protected $client;

    /**
     * Cos constructor.
     * 分片上传初始化
     */
    public function __construct()
    {
        $secretId = ConfigService::getValue(config("setting.tencent.secretId")); //"云 API 密钥 SecretId";
        $secretKey = ConfigService::getValue(config("setting.tencent.secretKey")); //"云 API 密钥 SecretKey";
        $region = ConfigService::getValue(config("setting.tencent.region")); //设置一个默认的存储桶地域
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials' => array(
                    'secretId' => $secretId,
                    'secretKey' => $secretKey
                )
            )
        );
        $this->client = $cosClient;
    }

    /**
     * Author:Zhongyuan Lu
     * 分片上传 获取唯一UploadId
     * @param $filename
     * @return array
     */
    public function bigCos($filename)
    {
        Redis::select(5);
        try {
            $result = $this->client->createMultipartUpload(array(
                'Bucket' => ConfigService::getValue(config("setting.tencent.bucket")), //格式：BucketName-APPID
                'Key' => $filename,
            ));
            Redis::set($filename . 'upload', $result['UploadId'], 600);
            Redis::set($filename . 'key', $result['Key'], 600);
            Redis::set($filename . 'bucket', $result['Bucket'], 600);
        } catch (\Exception $e) {
            // 请求失败
            return ['code' => '400', 'data' => $e, 'message' => $e->getMessage()];
        }
    }

    /**
     * Author:Zhongyuan Lu
     * 分片上传
     * @param $path
     * @param $params
     * @param $filename
     * @return array
     */
    public function bigCoss($path, $params, $filename)
    {
        Redis::select(5);
        if ($params['page'] == 1) {
            self::bigCos($filename);
        }
        $uploadId = Redis::get($filename . 'upload');
        $key = Redis::get($filename . 'key');
        $bucket = Redis::get($filename . 'bucket');
        try {
            $result = $this->client->uploadPart(array(
                'Bucket' => $bucket, //格式：BucketName-APPID
                'Key' => $key,
                'Body' => $path,
                'UploadId' => $uploadId, //UploadId 为对象分块上传的 ID，在分块上传初始化的返回参数里获得
                'PartNumber' => $params['page'], //PartNumber 为分块的序列号，COS 会根据携带序列号合并分块
            ));
            return ['ETag' => $result['ETag'], 'PartNumber' => $params['page']];
        } catch (\Exception $e) {
            // 请求失败
            return ['code' => '400', 'data' => $e, 'message' => $e->getMessage()];
        }
    }

    /**
     * Author:Zhongyuan Lu
     * 分片上床最终合并文件
     * @param $arr
     * @param $filename
     * @return array
     */
    public function complete($arr, $filename)
    {
        Redis::select(5);
        $uploadId = Redis::get($filename . 'upload');
        $key = Redis::get($filename . 'key');
        $bucket = Redis::get($filename . 'bucket');
        try {
            $this->client->completeMultipartUpload(array(
                'Bucket' => $bucket,
                'Key' => $key,
                'UploadId' => $uploadId,
                'Parts' => $arr
            ));
        } catch (\Exception $e) {
            // 请求失败
            return ['code' => '400', 'data' => $e, 'message' => $e->getMessage()];
        }
    }

    /**
     * william
     * 文件上传
     * @param $fileName
     * @param $filePath
     * @return string
     */
    public function uoloadFile($fileName,$filePath)
    {
        $secretId = env('COS_SECRET_ID'); //"云 API 密钥 SecretId";
        $secretKey = env('COS_SECRET_KEY'); //"云 API 密钥 SecretKey";
        $region = env('COS_REGION'); //设置一个默认的存储桶地域
        $cosClient = new \Qcloud\Cos\Client(
            array(
                'region' => $region,
                'schema' => 'https', //协议头部，默认为http
                'credentials' => array(
                    'secretId' => $secretId,
                    'secretKey' => $secretKey
                )
            )
        );
        ### 上传文件流
        try {
            $bucket = env('COS_BUCKET'); //存储桶名称 格式：BucketName-APPID
            $key = $fileName; //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
            $srcPath = $filePath;//本地文件绝对路径
            $file = fopen($srcPath, "rb");
            if ($file) {
                $result = $cosClient->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file));
            }
            return ['code' => '200', 'data' => "http://".$result['Location'], 'message' => '上传成功'];
        } catch (\Exception $e) {
            return ['code' => '400', 'data' => $e, 'message' => $e->getMessage()];
        }
    }
}
